/**
 * Vue i18n loader
 * created by @musnow
 * https://github.com/musnow
 */
import Vue from 'vue';
import VueI18n from 'vue-i18n';
// default language
import zhCN from './lang/zh-CN';
import enUS from './lang/en-US';
import zhTW from './lang/zh-TW';
import jaJP from './lang/ja-JP';
import thTH from './lang/th-TH';
// change default accept-language
import { axios } from '@/utils/request';

Vue.use(VueI18n);

export const defaultLang = 'zh-CN';

const messages = {
  'zh-CN': {
    ...zhCN
  },
  'en-US': {
    ...enUS
  },
  'zh-TW': {
    ...zhTW
  },
  'ja-JP': {
    ...jaJP
  },
  'th-TH': {
    ...thTH
  }
};

const i18n = new VueI18n({
  locale: defaultLang,
  fallbackLocale: defaultLang,
  messages
});

export default i18n;

const loadedLanguages = [defaultLang];

function setI18nLanguage (lang) {
  i18n.locale = lang;
  axios.defaults.headers.common['Accept-Language'] = lang;
  axios.defaults.headers.locale = lang;
  document.querySelector('html').setAttribute('lang', lang);
  return lang;
}

/**
 * i18n Render
 * @param key
 * @returns rendered string
 */
export function i18nRender (key) {
  return i18n.t(key);
}

export function loadLanguageAsync (lang = defaultLang) {
  return new Promise(resolve => {
    // 缓存语言设置
    Vue.ls.set('LANG', lang);
    if (i18n.locale !== lang) {
      if (!loadedLanguages.includes(lang)) {
        return import(/* webpackChunkName: "lang-[request]" */ `./lang/${lang}`).then(msg => {
          i18n.setLocaleMessage(lang, msg.default);
          loadedLanguages.push(lang);
          return setI18nLanguage(lang);
        });
      }
      return resolve(setI18nLanguage(lang));
    }
    return resolve(lang);
  });
}
